<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.productId" clearable :placeholder="$t('tracibility.productId')" style="width: 250px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.productSn" clearable :placeholder="$t('tracibility.productSn')" style="width: 250px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
    </div>
    <p>{{ $t('produce.processList') }}</p>
    <el-collapse v-for="process in list" :key="process.uniqueId">
      <el-collapse-item v-if="process.bomResults.length !== 0">
        <template slot="title">
          <div style="width:100%;">
            <el-tag class="resultSpan">
              {{ process.testTime }}
            </el-tag>
            <el-tag class="resultSpan">
              {{ $t('equipment.lineNumber') + ': '+ process.lineNumber }}
            </el-tag>
            <el-tag>
              {{ $t('equipment.stationNumber') + ': '+ process.stationNumber }}
            </el-tag>
            <el-tag>
              {{ $t('equipment.processNumber') + ': '+ process.processNumber }}
            </el-tag>
          </div>
        </template>
        <template>
          <el-table
            :key="tableKey"
            v-loading="listLoading"
            :data="process.bomResults"
            :header-row-style="{color: 'black'}"
            :header-cell-style="{background: 'lightBlue'}"
            border
            fit
            highlight-current-row
            :row-style="{height:'20px'}"
            :cell-style="{padding:'2px'}"
            style="padding: 0px,width: 100%;"
          >
            <el-table-column :label="$t('bom.bomCode')" width="150px" align="center">
              <template slot-scope="{row}">
                <span>{{ row.bomCode }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('bom.bomName')" width="auto" align="center">
              <template slot-scope="{row}">
                <span>{{ row.bomName }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('bom.bomValue')" width="220px" align="center">
              <template slot-scope="{row}">
                <span>{{ row.bomValue }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('bom.bomLot')" width="100px" align="center">
              <template slot-scope="{row}">
                <span>{{ row.bomLot }}</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-collapse-item>
    </el-collapse>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import { getBomProcessList } from '@/api/bom'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'

export default {
  name: 'BomProcessSummary',
  components: {
    Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editRight: true,
      tableKey: 0,
      list: [],
      total: 0,
      activeName: 1,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        productSn: '',
        productId: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+test_time'
      },
      showReviewer: false,
      temp: {
        id: 0,
        projectNo: '',
        description: '',
        priority: '',
        manager: '',
        dueDate: '',
        startDate: '',
        state: 0,
        remark: '',
        companyCode: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        lineName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        lineNo: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        priority: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        company: false,
        manager: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        company: false,
        manager: false
      }
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (this.$route.query.productId !== undefined) {
          this.listQuery.productId = this.$route.query.productId
          this.getList()
        }
      }
    }
  },
  created() {
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    this.listQuery.productId = this.$route.query.productId
    this.getList()
  },
  methods: {
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 获取清单
    getList() {
      this.listLoading = true
      this.list = []
      getBomProcessList(this.listQuery).then(response => {
        this.list = response.data.bomProcesses
        this.total = response.data.total
      }).finally(() => { this.listLoading = false })
    },
    // 查看工艺数据
    handleProcessData(row) {
      const ret = Object.assign({}, row) // copy obj
      this.$router.push({ path: '/tracibility/dataSummary', query: { processId: ret.processId }})
    },
    // 查看错误信息
    handleCheck(row) {
      const ret = Object.assign({}, row) // copy obj
      if (ret.errMsg === null | '') {
        return
      }
      this.$msgbox({
        message: ret.errMsg,
        type: 'error'
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序时调用
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'startDate') {
        this.sortByCreatTime(order)
      } else if (prop === 'dueDate') {
        this.sortBydueDate(order)
      } else if (prop === 'priority') {
        this.sortByPriority(order)
      }
    },
    // 根据创建时间排序
    sortByCreatTime(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+start_date'
      } else {
        this.listQuery.sort = '-start_date'
      }
      this.handleFilter()
    },
    // 根据交期排序
    sortBydueDate(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+due_date'
      } else {
        this.listQuery.sort = '-due_date'
      }
      this.handleFilter()
    },
    // 根据优先级
    sortByPriority(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+priority'
      } else {
        this.listQuery.sort = '-priority'
      }
      this.handleFilter()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        id: 0,
        projectNo: '',
        description: '',
        priority: '',
        manager: '',
        dueDate: '',
        startDate: '',
        state: 0,
        remark: '',
        companyCode: ''
      }
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('tracibility.productId'),
          i18n.t('tracibility.productSn'),
          i18n.t('equipment.lineNumber'),
          i18n.t('equipment.stationNumber'),
          i18n.t('equipment.processNumber'),
          i18n.t('tracibility.testTime'),
          i18n.t('produce.typeNo'),
          i18n.t('produce.trayIdentifier'),
          i18n.t('produce.plcNo'),
          i18n.t('tracibility.processStatus')]
        const filterVal = ['productId', 'productSn', 'lineNumber', 'stationNumber', 'processNumber',
          'testTime', 'typeNo', 'trayIdentifier', 'plcNo', 'processStatus']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '工艺清单' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.processList.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}
.resultSpan {
  margin-left: 10px;
  margin-right: 100px;
}
@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
